package queue;

import linkedList.LinkedList;

public class LinkedListQueue<E> implements Queue<E> {
    private class Node {
        public Node next;
        public E e;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }
        @Override
        public String toString(){
            return e.toString();
        }
    }

    private Node head,tail;
    private int size;
    public LinkedListQueue(){
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    // 入队
    @Override
    public void enqueue(E e) {
        // 入队的操作就是根据tail尾指针在这个队列的末尾添加一个node节点
        // 有一个特殊情况,那就是队列中没有节点的时候,那么就需要new一个node节点,然后让头尾指针都指向这个节点
        if (tail == null){
            tail = new Node(e);
            head = tail;
        }else {
            tail.next =  new Node(e);
            tail = tail.next;
        }
        size++;
    }

    // 出队
    @Override
    public E dequeue() {
        // 出队首先需要判断队列是否为空,如果为空的话,那么就无法执行出队操作了
        if (isEmpty()){
            throw new IllegalArgumentException("cannot dequeue from an empty queue.");
        }
        Node oldHead = head;
        head = head.next;
        oldHead.next = null;
        // 这里需要注意的是,如果队列中只剩下一个元素,那么出队的那个元素也是尾指针指向的元素,这个时候应该让尾指针也为null;
        if (head == null){
            tail = null;
        }
        size--;
        return oldHead.e;
    }

    @Override
    public E getFront() {
        if (isEmpty()){
            throw new IllegalArgumentException("queue is empty.");
        }
        return head.e;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Queue : front ");
        Node current;
        for (current = head; current != null; current = current.next){
            sb.append(current.e + " --> ");
        }
        sb.append("null");
        return sb.toString();
    }
}
